package com.zb.kc.vod.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.zb.kc.commonutils.ExceptionUtil;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import com.zb.kc.vod.service.VodService;
import com.zb.kc.vod.utils.ConstantVodUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class VodServiceImpl implements VodService {

    /**
     * 上传视频到阿里云
     *
     * @param file
     * @return
     */
    @Override
    public String uploadAlyVideo(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error(ExceptionUtil.getMessage(e));
            throw new KgcException(50000, e.getMessage());
        }
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        return uploadStream(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
    }

    /**
     * 根据阿里云的视频id删除视频
     *
     * @param id
     */
    @Override
    public void deleteVideo(String id) {
        DefaultAcsClient client = initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
        DeleteVideoRequest request = new DeleteVideoRequest();
        DeleteVideoResponse response = new DeleteVideoResponse();
        //支持传入多个视频ID，多个用逗号分隔
        request.setVideoIds(id);
        try {
            response = client.getAcsResponse(request);
        } catch (com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
            log.error(ExceptionUtil.getMessage(e));
            throw new KgcException(50000, e.getErrMsg());
        }
    }

    /**
     * 批量删除阿里云的视频
     * @param videIdList
     */
    @Override
    public void removeMoreAlyVideo(List<String> videIdList) {
        DefaultAcsClient client = initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
        DeleteVideoRequest request = new DeleteVideoRequest();
        DeleteVideoResponse response = new DeleteVideoResponse();
        // 阿里云最多只能一次性删除20个所以分组
        List<List<String>> splitVideIdList = Lists.partition(videIdList, 20);
        for (List list : splitVideIdList) {
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(Joiner.on(",").join(list));
            try {
                response = client.getAcsResponse(request);
            } catch (com.aliyuncs.exceptions.ClientException e) {
                e.printStackTrace();
                log.error(ExceptionUtil.getMessage(e));
                throw new KgcException(50000, e.getErrMsg());
            }
        }
    }

    /**
     * 初始化请求客户端
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws ClientException
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }


    /**
     * 流式上传接口
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param title
     * @param fileName
     * @param inputStream
     */
    private String uploadStream(String accessKeyId, String accessKeySecret, String title, String fileName, InputStream inputStream) {
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
        request.setTemplateGroupId("dfb397de426076ae582557f259fe0939");
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        String videoId = null;
        if (response.isSuccess()) {
            videoId = response.getVideoId();
        } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            videoId = response.getVideoId();
        }
        return videoId;
    }

}
